﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Data.Objects;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using FILSTARTUPS_CMS.Models;

namespace FILSTARTUPS_CMS.Controllers
{

    [Authorize]
    public class PostController : Controller
    {
        FilStartUpsEntities cms_dbconnect = new FilStartUpsEntities();
        //
        // GET: /Post/
        [HttpPost]
        public JsonResult GetPost(string query, int catid)
        {
            if (catid == 0)
            {
                var post = (from p in cms_dbconnect.Post
                            where p.posttitle.Contains(query)
                            orderby p.posttitle
                            select p.posttitle).Distinct().ToArray();

                return Json(post, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var post = (from p in cms_dbconnect.Post
                            where p.posttitle.StartsWith(query)
                           && p.catidFK.Equals(catid)
                            orderby p.posttitle
                            select p.posttitle).Distinct().ToArray();

                return Json(post, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Index()
        {
            var post = (from p in cms_dbconnect.Post
                        join c in cms_dbconnect.Categories on p.catidFK equals c.catidPK
                        join v in cms_dbconnect.RoutingType on p.routingidFK equals v.routingidPK
                        select new PostGrid
                        {
                            viewtype = v.routingname,
                            categoryname = c.categoryname,
                            postidPK = p.postidPK,
                            posttitle = p.posttitle,
                            datecreated = p.datecreated
                        }).ToList().OrderByDescending(p => p.postidPK);

            ViewData["category"] = cms_dbconnect.Categories.OrderBy(c => c.catidPK).ToList();

            return View(post);
        }

        //Partial View
        public PartialViewResult SearchCategory(string query, int catidFK)
        {
            if (query == "" || query == null)
            {
                var categorypost = (from p in cms_dbconnect.Post
                                    join c in cms_dbconnect.Categories
                                    on p.catidFK equals c.catidPK
                                    join v in cms_dbconnect.RoutingType
                                    on p.routingidFK equals v.routingidPK
                                    where c.catidPK.Equals(catidFK)
                                    select new PostGrid
                                    {
                                        viewtype = v.routingname,
                                        categoryname = c.categoryname,
                                        datecreated = p.datecreated,
                                        postidPK = p.postidPK,
                                        posttitle = p.posttitle,
                                    }).ToList();
                return PartialView("_PostList", categorypost);

            }
            else
            {
                var categorypost = (from p in cms_dbconnect.Post
                                    join c in cms_dbconnect.Categories
                                    on p.catidFK equals c.catidPK
                                    join v in cms_dbconnect.RoutingType
                                    on p.routingidFK equals v.routingidPK
                                    where c.catidPK.Equals(catidFK)
                                    && p.posttitle.Equals(query)
                                    select new PostGrid
                                    {
                                        viewtype = v.routingname,
                                        categoryname = c.categoryname,
                                        datecreated = p.datecreated,
                                        postidPK = p.postidPK,
                                        posttitle = p.posttitle,
                                    }).ToList();

                return PartialView("_PostList", categorypost);

            }
        }

        public ActionResult Create()
        {
            ViewData["catidPK"] = cms_dbconnect.Categories.Where(cat => cat.categoryname != "Events").OrderBy(c => c.catidPK).ToList();
            ViewData["routingidFK"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Create(Post post, HttpPostedFileBase postimage, FormCollection form)
        {

            var userpost = cms_dbconnect.Users.Where(u => u.Username == User.Identity.Name).SingleOrDefault();

            if (postimage != null)
            {
                post.imagetype = postimage.ContentType;
                post.filename = postimage.FileName;
                int lenght = postimage.ContentLength;
                byte[] buffer = new byte[lenght];
                postimage.InputStream.Read(buffer, 0, lenght);
                post.image = buffer;
            }

            if (ModelState.IsValid)
            {
                if (form["postdescription"].Trim() == string.Empty)
                {
                    //ViewData["posttitle"] = form["posttitle"].Trim();
                    //ViewData["catidPK"] = cms_dbconnect.Categories.OrderBy(c => c.catidPK).ToList();
                    //ViewData["routingidFK"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
                    //TempData["message"] = string.Format("Post Description is empty");
                    return View(post);
                }
                else
                {


                    post.catidFK = Convert.ToInt32(form["catidPK"].Trim());
                    post.routingidFK = Convert.ToInt32(form["routingidFK"].Trim());
                    post.useridFK = userpost.useridPK;
                    post.datecreated = DateTime.Now;
                    cms_dbconnect.Post.Add(post);
                    cms_dbconnect.SaveChanges();
                    TempData["message"] = string.Format("{0} has been saved", post.posttitle);
                    return RedirectToAction("Index");
                }
            }


            return View();
        }


        /**** EVENT ID MAY VARY ****/
        public ActionResult CreateEvent()
        {
            ViewData["routingidFK"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
            return View();
        }

        /**** EVENT ID MAY VARY ****/
        [HttpPost, ValidateInput(false)]
        public ActionResult CreateEvent(Event events, FormCollection form)
        {
            try
            {
                var userpost = cms_dbconnect.Users.Where(u => u.Username == User.Identity.Name).SingleOrDefault();

                if (ModelState.IsValid)
                {
                    if (form["eventdescription"].Trim() == string.Empty)
                    {
                        ViewData["routingidFK"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
                        TempData["message"] = string.Format("Post Description is empty!");
                        return View();
                    }
                    else
                    {

                        events.routingidFK = Convert.ToInt32(form["routingid"].Trim());
                        events.datecreated = DateTime.Now;
                        events.useridFK = userpost.useridPK;
                        events.eventdatestart = Convert.ToDateTime(form["from"].Trim());
                        events.eventdateend = Convert.ToDateTime(form["to"].Trim());
                        cms_dbconnect.Events.Add(events);
                        cms_dbconnect.SaveChanges();
                        TempData["message"] = string.Format("{0} has been saved", events.eventtitle);
                        return RedirectToAction("Index");
                    }
                }
            }
            catch
            {

            }
            return View();
        }
        public ActionResult Edit(int id)
        {
            Post post = cms_dbconnect.Post.Find(id);
            var category = cms_dbconnect.Categories.OrderBy(c => c.catidPK).ToList();
            var routing = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
            //IEnumerable<SelectListItem> i = new SelectList(category, "catidPK", "categoryname", post.catidFK);
            //ViewData["catidPK"] = i;
    
            ViewBag.catidPK = new SelectList(category, "catidPK", "categoryname", post.catidFK);
            ViewBag.routing = new SelectList(routing, "routingidPK", "routingname", post.routingidFK);
            return View(post);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(int id,
            FormCollection form, HttpPostedFileBase postpic)
        {


            var userpost = cms_dbconnect.Users.Where(u => u.Username == User.Identity.Name).SingleOrDefault();
            var post = cms_dbconnect.Post.Where(p => p.postidPK.Equals(id)).SingleOrDefault();
            try
            {
                if (ModelState.IsValid)
                {
                    if (postpic != null)
                    {

                        post.imagetype = postpic.ContentType;
                        post.filename = postpic.FileName;
                        int lenght = postpic.ContentLength;
                        byte[] buffer = new byte[lenght];
                        postpic.InputStream.Read(buffer, 0, lenght);
                        post.image = buffer;
                    }
                    string featured = form["featuredpost"];

                    if (featured != null)
                    {
                        post.featuredpost = true;
                    }
                    else
                    {
                        post.featuredpost = false;
                    }
                    post.posttitle = form["posttitle"].Trim();
                    post.postdescription = form["postdescription"].Trim();
                    post.datecreated = DateTime.Today;
                    post.catidFK = Convert.ToInt32(form["catidPK"].Trim());
                    post.routingidFK = Convert.ToInt32(form["routing"].Trim());
                    post.useridFK = userpost.useridPK;

                    cms_dbconnect.Entry(post).State = EntityState.Modified;
                    cms_dbconnect.SaveChanges();
                    TempData["message"] = string.Format("{0} has been modified", post.posttitle);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception)
            {

            }
            return null;
        }



        public ActionResult Details(int id)
        {
            var post = (from p in cms_dbconnect.Post
                        join r in cms_dbconnect.RoutingType
                        on p.routingidFK equals r.routingidPK
                        join c in cms_dbconnect.Categories
                        on p.catidFK equals c.catidPK
                        where p.postidPK.Equals(id)
                        select new PostGrid
                        {
                            filename=p.filename,
                            categoryname = c.categoryname,
                            datecreated = p.datecreated,
                            postidPK = p.postidPK,
                            postdescription = p.postdescription,
                            posttitle = p.posttitle,
                            viewtype = r.routingname
                        }).SingleOrDefault();

            return View(post);
        }


        /*** IMAGE ***/
        public ActionResult PostPicture(int id)
        {
            try
            {
                var postpic = cms_dbconnect.Post.Where(p => p.postidPK.Equals(id)).SingleOrDefault();
                byte[] image = postpic.image;
                return File(image, postpic.imagetype);
            }
            catch
            {
                return null;
            }
        }


        /** TEST 
        public ActionResult TestModel()
        {
            var TotalPost = new TotalPost();

            TotalPost.post_ = cms_dbconnect.Post.OrderBy(p => p.postidPK).ToList();

            TotalPost.cat_ = cms_dbconnect.Categories.OrderBy(c => c.catidPK).ToList();

            return View(TotalPost);
        }

        public PartialViewResult FilterCategory(string CategoryType)
        {
            return PartialView();
        } **/
    }
}
